"use client";
import UpdateModal from "./components/UpdateModal";
import {
  deleteFriendUsingPost,
  queryFriendShipListUsingPost,
  agreeFriendUsingPost,
  rejectFriendUsingPost,
  renameFriendUsingPost,
} from "@/api/userRelationshipController";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, message, Modal, Space, Typography } from "antd";
import React, { useRef, useState } from "react";
import {useSelector} from "react-redux";
import {RootState} from "@/stores";

/**
 * 好友管理页面
 */
const FriendAdminPage: React.FC = () => {
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前点击的数据
  const [currentRow, setCurrentRow] =
    useState<API.FunRiceUserRelationshipAddthumb>();

  /**
   * 删除好友
   */
  const confirmDelete = async (record: API.FunRiceUserRelationshipAddthumb) => {
    Modal.confirm({
      title: "确认删除好友吗？",
      content: `确定要删除好友 ${record.userAccount} 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        await handleDelete(record);
      },
    });
  };
  const loginUser = useSelector((state: RootState) => state.loginUser);

  const handleDelete = async (row: API.FunRiceUserRelationshipAddthumb) => {
    const currentUserAccount = loginUser.userAccount;
    const targetAccount = row.userAccount === currentUserAccount
        ? row.friendsUserAccount
        : row.userAccount;
    if (currentUserAccount!==row.friendsUserAccount&&currentUserAccount!==row.userAccount) {
      message.error("您们还不是好友");
      return false;
    }
    const hide = message.loading("正在删除");
    if (!row) return true;
    try {
      await deleteFriendUsingPost({
        friendsUserAccount: targetAccount,
      });
      hide();
      message.success("删除成功");
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error(error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.FunRiceUserRelationshipAddthumb>[] = [
    {
      title: "A饭点id",
      dataIndex: "userId",
      valueType: "text",
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: "A饭点号",
      dataIndex: "userAccount",
      valueType: "text",
    },
    {
      title: "B饭点id",
      dataIndex: "friendsId",
      valueType: "text",
      hideInSearch: true,
    },

    {
      title: "B饭点号",
      dataIndex: "friendsUserAccount",
      valueType: "text",
    },
    {
      title: "A备注",
      dataIndex: "afriendsNameRemarks",
      valueType: "text",
    },
    {
      title: "B备注",
      dataIndex: "bfriendsNameRemarks",
      valueType: "text",
    },
    {
      title: "状态",
      dataIndex: "reviewStatus",
      valueType: "select",
      fieldProps: {
        allowClear: true,
        placeholder: "请选择状态"
      },
      valueEnum: {
        0: { text: "待审核", status: "Processing" },
        1: { text: "已同意", status: "Success" },
      }
    },
    {
      title: "申请时间",
      dataIndex: "createTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true,
      sorter: true,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => {
        const operations = [];
        
        // 修改备注按钮
        operations.push(
          <Typography.Link
            key="edit"
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改备注
          </Typography.Link>
        );

        // 根据状态显示不同的操作按钮
        if (record.reviewStatus === 0) {
          operations.push(
            <Typography.Link
              key="agree"
              onClick={async () => {
                const hide = message.loading("正在处理");
                try {
                  await agreeFriendUsingPost({
                    //@ts-ignore
                    userId: record.userId,
                  });
                  hide();
                  message.success("已同意");
                  actionRef.current?.reload();
                } catch (error: any) {
                  hide();
                  message.error(error.message);
                }
              }}
            >
              同意
            </Typography.Link>,
            <Typography.Link
              key="reject"
              onClick={async () => {
                const hide = message.loading("正在处理");
                try {
                  await rejectFriendUsingPost({
                    //@ts-ignore
                    userId: record.userId,
                  });
                  hide();
                  message.success("已拒绝");
                  actionRef.current?.reload();
                } catch (error: any) {
                  hide();
                  message.error(error.message);
                }
              }}
            >
              拒绝
            </Typography.Link>
          );
        }

        // 删除按钮
        operations.push(
          <Typography.Link
            key="delete"
            type="danger"
            onClick={() => confirmDelete(record)}
          >
            删除
          </Typography.Link>
        );

        return <Space size="middle">{operations}</Space>;
      },
    },
  ];

  return (
    <div
      id="admin-friend"
      style={{
        width: "100%",
        marginTop: 0,
        display: "flex",
        margin: "0 auto",
        marginLeft: "20px",
      }}
    >
      <PageContainer
        title={null}
        // 将 title 设为 null
        header={{
          title: null,
          breadcrumb: {
            items: [
              // { title: '用户管理' },
            ],
          },
        }}
      >
        <ProTable<API.FunRiceUserRelationshipAddthumb>
          headerTitle={null}
          options={false}
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 80,
            defaultCollapsed: false,
            style: {
              marginBottom: "24px",
            },
          }}
          //@ts-ignore
          request={async (params,filter) => {
            const requestParams = {
              ...params,
              sortField: params.sortField || "createTime",
              sortOrder: params.sortOrder || "desc",
              ...filter,
            };
            

            
            const { data } = await queryFriendShipListUsingPost(requestParams as API.UserQueryFriendShipListRequest);
            return {
              success: true,
              data: data || [],
            };
          }}
          pagination={{
            showTotal(total: number) {
              return "总数：" + total;
            },
            pageSize: 10,
          }}
          columns={columns}
          scroll={{ x: 1400 }}
        />
        <UpdateModal
          visible={updateModalVisible}
          columns={columns}
            //@ts-ignore
          oldData={{
            ...currentRow,
            bfriendsNameRemarks: currentRow?.bfriendsNameRemarks || '' // 确保有默认值
          }}
          onSubmit={() => {
            setUpdateModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          }}
          onCancel={() => {
            setUpdateModalVisible(false);
          }}
        />
      </PageContainer>
    </div>
  );
};

export default FriendAdminPage;
